import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

class Student {
    private String name;
    private String studentId;
    private Map<String, Double> courseScores;

    public Student(String name, String studentId) {
        this.name = name;
        this.studentId = studentId;
        this.courseScores = new HashMap<>();
    }

    public String getName() {
        return name;
    }

    public String getStudentId() {
        return studentId;
    }

    public Map<String, Double> getCourseScores() {
        return courseScores;
    }

    public void addCourseScore(String course, double score) {
        courseScores.put(course, score);
    }
}

class GradeManager {
    private List<Student> students;

    public GradeManager() {
        this.students = new ArrayList<>();
    }

    public boolean addStudent(String name, String studentId) {
        if (findStudentById(studentId) != null) {
            return false;
        }
        students.add(new Student(name, studentId));
        return true;
    }

    public boolean addScore(String studentId, String course, double score) {
        Student student = findStudentById(studentId);
        if (student == null) {
            return false;
        }
        student.addCourseScore(course, score);
        return true;
    }

    public Student findStudentById(String studentId) {
        for (Student student : students) {
            if (student.getStudentId().equals(studentId)) {
                return student;
            }
        }
        return null;
    }

    public List<Student> findStudentsByName(String name) {
        List<Student> result = new ArrayList<>();
        for (Student student : students) {
            if (student.getName().equals(name)) {
                result.add(student);
            }
        }
        return result;
    }

    public List<Student> findStudentsByCourse(String course) {
        List<Student> result = new ArrayList<>();
        for (Student student : students) {
            if (student.getCourseScores().containsKey(course)) {
                result.add(student);
            }
        }
        return result;
    }

    public double calculateAverageScore(String course) {
        List<Student> studentsWithCourse = findStudentsByCourse(course);
        if (studentsWithCourse.isEmpty()) {
            return 0;
        }
        double sum = 0;
        for (Student student : studentsWithCourse) {
            sum += student.getCourseScores().get(course);
        }
        return sum / studentsWithCourse.size();
    }

    public double findMaxScore(String course) {
        List<Student> studentsWithCourse = findStudentsByCourse(course);
        if (studentsWithCourse.isEmpty()) {
            return 0;
        }
        double max = Double.MIN_VALUE;
        for (Student student : studentsWithCourse) {
            double score = student.getCourseScores().get(course);
            if (score > max) {
                max = score;
            }
        }
        return max;
    }

    public double findMinScore(String course) {
        List<Student> studentsWithCourse = findStudentsByCourse(course);
        if (studentsWithCourse.isEmpty()) {
            return 0;
        }
        double min = Double.MAX_VALUE;
        for (Student student : studentsWithCourse) {
            double score = student.getCourseScores().get(course);
            if (score < min) {
                min = score;
            }
        }
        return min;
    }
}

public class StudentGradeSystem {
    private static final Scanner scanner = new Scanner(System.in);
    private static final GradeManager gradeManager = new GradeManager();

    public static void main(String[] args) {
        while (true) {
            showMainMenu();
            int choice = getIntInput("输入选项序号：");
            switch (choice) {
                case 1:
                    recordGrade();
                    break;
                case 2:
                    queryGrade();
                    break;
                case 3:
                    statisticsGrade();
                    break;
                case 4:
                    System.out.println("感谢使用学生成绩管理系统，再见");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    private static void showMainMenu() {
        System.out.println("=================================");
        System.out.println("欢迎使用学生成绩管理系统");
        System.out.println("=================================");
        System.out.println("请选择操作：");
        System.out.println("1. 记录学生成绩");
        System.out.println("2. 查询学生成绩");
        System.out.println("3. 统计课程成绩");
        System.out.println("4. 退出系统");
    }

    private static void recordGrade() {
        System.out.println("===== 记录学生成绩 =====");
        String name = getStringInput("请输入学生姓名：");
        String studentId = getStringInput("请输入学生学号：");

        if (!gradeManager.addStudent(name, studentId)) {
            System.out.println("错误：该学号已存在！");
            return;
        }

        String course = getStringInput("输入课程名称：");
        double score = getDoubleInput("请输入成绩（0-100）：", 0, 100);

        if (gradeManager.addScore(studentId, course, score)) {
            System.out.println("成绩已成功记录！");
        } else {
            System.out.println("记录成绩失败！");
        }
    }

    private static void queryGrade() {
        System.out.println("===== 查询学生成绩 =====");
        System.out.println("请选择查询方式：");
        System.out.println("1. 按学生姓名查询");
        System.out.println("2. 按学生学号查询");
        System.out.println("3. 按课程名称查询");
        int queryChoice = getIntInput("请输入选项序号：");

        switch (queryChoice) {
            case 1:
                String name = getStringInput("请输入学生姓名：");
                List<Student> studentsByName = gradeManager.findStudentsByName(name);
                if (studentsByName.isEmpty()) {
                    System.out.println("未找到该学生的成绩记录！");
                } else {
                    for (Student student : studentsByName) {
                        printStudentScores(student);
                    }
                }
                break;
            case 2:
                String studentId = getStringInput("请输入学生学号：");
                Student student = gradeManager.findStudentById(studentId);
                if (student == null) {
                    System.out.println("未找到该学生的成绩记录！");
                } else {
                    printStudentScores(student);
                }
                break;
            case 3:
                String course = getStringInput("请输入课程名称：");
                List<Student> studentsByCourse = gradeManager.findStudentsByCourse(course);
                if (studentsByCourse.isEmpty()) {
                    System.out.println("未找到该课程的成绩记录！");
                } else {
                    for (Student s : studentsByCourse) {
                        System.out.printf("姓名：%s, 学号：%s, 课程：%s, 成绩：%.1f%n",
                                s.getName(), s.getStudentId(), course, s.getCourseScores().get(course));
                    }
                }
                break;
            default:
                System.out.println("无效的查询选项！");
        }
    }

    private static void statisticsGrade() {
        System.out.println("===== 统计课程成绩 =====");
        String course = getStringInput("输入课程名称：");
        List<Student> studentsWithCourse = gradeManager.findStudentsByCourse(course);

        if (studentsWithCourse.isEmpty()) {
            System.out.println("未找到该课程的成绩记录！");
            return;
        }

        double average = gradeManager.calculateAverageScore(course);
        double max = gradeManager.findMaxScore(course);
        double min = gradeManager.findMinScore(course);

        System.out.printf("课程：%s%n", course);
        System.out.printf("平均分：%.2f%n", average);
        System.out.printf("最高分：%.1f%n", max);
        System.out.printf("最低分：%.1f%n", min);
    }

    private static void printStudentScores(Student student) {
        Map<String, Double> scores = student.getCourseScores();
        if (scores.isEmpty()) {
            System.out.printf("姓名：%s, 学号：%s, 暂无成绩记录！%n", student.getName(), student.getStudentId());
        } else {
            for (Map.Entry<String, Double> entry : scores.entrySet()) {
                System.out.printf("姓名：%s, 学号：%s, 课程：%s, 成绩：%.1f%n",
                        student.getName(), student.getStudentId(), entry.getKey(), entry.getValue());
            }
        }
    }

    private static String getStringInput(String prompt) {
        System.out.print(prompt);
        return scanner.nextLine();
    }

    private static int getIntInput(String prompt) {
        while (true) {
            try {
                System.out.print(prompt);
                int input = Integer.parseInt(scanner.nextLine());
                return input;
            } catch (NumberFormatException e) {
                System.out.println("输入无效，请输入一个整数！");
            }
        }
    }

    private static double getDoubleInput(String prompt, double min, double max) {
        while (true) {
            try {
                System.out.print(prompt);
                double input = Double.parseDouble(scanner.nextLine());
                if (input < min || input > max) {
                    System.out.printf("输入无效，请输入%.1f-%.1f之间的数字！%n", min, max);
                } else {
                    return input;
                }
            } catch (NumberFormatException e) {
                System.out.println("输入无效，请输入一个数字！");
            }
        }
    }
}